package cn.classba.hive.json;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;


@Description(name = "json_array",
        value = "_FUNC_(array_string) - Convert a string of a JSON-encoded array to a Hive array of strings.")
public class JsonArray extends UDF {
    public ArrayList<Text> evaluate(String jsonString) {
        if (jsonString == null) {
            return null;
        }
        try {
            JSONArray extractObject = new JSONArray(jsonString);
            ArrayList<Text> result = new ArrayList<Text>();
            for (int ii = 0; ii < extractObject.length(); ++ii) {
                String s = extractObject.get(ii).toString();
                result.add(new Text(s));
            }
            return result;
        } catch (JSONException | NumberFormatException e) {
            e.printStackTrace();
            return null;
        }
    }

}